﻿using ConfExpert.Forms.Base;
using DevExpress.Utils;
using DevExpress.XtraCharts;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Araclar
{
    public partial class TCMB : XForm
    {
        public TCMB()
        {
            InitializeComponent();
            //
            //txtInfo.Caption = "- TCMB Döviz Kurları";
        }

        BindingSource bsDaily, bsChart;
        DateTime start = new DateTime(2010, 1, 1), end = DateTime.Today;
        private void TCMB_Load(object sender, EventArgs e)
        {
            

            ds.xTCMB2.Columns.Add("EUR/USD", typeof(float), "EUR/USD");
            bsDaily = new BindingSource(ds, "xTCMB1");
            bsChart = new BindingSource(ds, "xTCMB2");

            InitGridView(gvDaily, bsDaily);
            gvDaily.Columns["Tarih"].Visible = false;
            gvDaily.OptionsView.ColumnAutoWidth = true;
            gvDaily.OptionsView.ShowGroupPanel = false;

            gvDaily.Columns["Selling"].DisplayFormat.FormatType = gvDaily.Columns["Buying"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            gvDaily.Columns["Selling"].DisplayFormat.FormatString = gvDaily.Columns["Buying"].DisplayFormat.FormatString = "c4"; // "#,###.##";
            gvDaily.OptionsCustomization.AllowFilter = false;
            gvDaily.OptionsView.ShowAutoFilterRow = false;

            gvDaily.Columns["Currency"].Caption = "DövizCinsi";
            gvDaily.Columns["Selling"].Caption = "Alış";
            gvDaily.Columns["Buying"].Caption = "Satış";

            gvDaily.OptionsView.ShowFooter = false;
            foreach (GridColumn col in gvDaily.Columns)
                col.OptionsColumn.AllowEdit = false;

            ViewType[] restrictedTypes = new ViewType[] { ViewType.PolarArea, ViewType.PolarLine, ViewType.SideBySideGantt,
				ViewType.SideBySideRangeBar, ViewType.RangeBar, ViewType.Gantt, ViewType.PolarPoint, ViewType.Stock, ViewType.CandleStick,
				ViewType.Bubble
			};

            foreach (ViewType type in Enum.GetValues(typeof(ViewType)))
            {
                if (Array.IndexOf<ViewType>(restrictedTypes, type) >= 0) continue;
                comboChartType.Properties.Items.Add(type);
            }


            deGun.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            deGun.Properties.DisplayFormat.FormatString = "dd/MM/yyyy dddd";
            deGun.EditValueChanged += new EventHandler(deGun_EditValueChanged);
            deGun.EditValue = DateTime.Now;

            GetDetails("xTCMB1;xTCMB2", "GetCurrency2", (DateTime)deGun.EditValue, 0, 1);
            
            gcDaily.MouseWheel += new MouseEventHandler(gridControl1_MouseWheel);
            chartControl1.MouseWheel += new MouseEventHandler(chartControl1_MouseWheel);
            DrawChart();

            comboChartType.SelectedIndexChanged += new EventHandler(comboChartType_SelectedIndexChanged);
            comboChartType.SelectedText = "Line";

            GridViewInfo info = gvDaily.GetViewInfo() as GridViewInfo;
            int height = info.CalcRealViewHeight(new Rectangle(0, 0, Int32.MaxValue, Int32.MaxValue));
            lblCapraz.Top -= (gcDaily.Height - height);
            gcDaily.Height = height;
            gcDaily.Focus();

            //RefreshCurr(0);
            chartControl1.Zoom += new ChartZoomEventHandler(chartControl1_Zoom);
            //chartControl1.RuntimeSelection = true;
            //chartControl1.MouseClick+=new MouseEventHandler(chartControl1_MouseClick);
            //chkLineMarker.CheckedChanged += new EventHandler(chkLineMarker_CheckedChanged);
            //chkLineMarker.Checked = true;
            //chkLineMarker.Tag = true;

            comboPeriod.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            comboPeriod.Properties.Items.AddRange(new object[] { "Month", "Year", "5Years" });
            comboPeriod.EditValueChanged += new EventHandler(comboPeriod_EditValueChanged);
            comboPeriod.EditValue = "Year";
        }

        void chkNoOverlap_CheckedChanged(object sender, EventArgs e)
        {
            ChkMarkerChanged();
        }

        bool prevzoomed = false, zoomed = false;
        void chartControl1_Zoom(object sender, ChartZoomEventArgs e)
        {
            zoomed = (e.AxisX.VisualRange.MaxValueInternal - e.AxisX.VisualRange.MinValueInternal < 100);
            if (zoomed != prevzoomed)
                ChkMarkerChanged();
            prevzoomed = zoomed;
        }

        //void chkLineMarker_CheckedChanged(object sender, EventArgs e)
        //{
        //    ChkMarkerChanged();
        //}

        private void ChkMarkerChanged()
        {
            LineMarker = chkLineMarker.Checked && ((bool)chkLineMarker.Tag || zoomed);
            for (int i = 0; i < chartControl1.Series.Count; i++)
            {
                DefaultBoolean visible = LineMarker ? DefaultBoolean.True:DefaultBoolean.False;
                chartControl1.Series[i].LabelsVisibility = visible; // az;
                //chartControl1.Series[i].Label.ResolveOverlappingMode = chkNoOverlap.Checked ? ResolveOverlappingMode.HideOverlapped/*JustifyAroundPoint*/ : ResolveOverlappingMode.None; ;
                chartControl1.Series[i].Label.Border.Visibility = DefaultBoolean.False;
                chartControl1.Series[i].Label.BackColor = Color.Transparent;
                if ((chartControl1.Series[i].View is LineSeriesView))
                    (chartControl1.Series[i].View as LineSeriesView).LineMarkerOptions.Size = LineMarker ? 10 : 1; //cok
            }
        }

        //ToolTipController toolTipController1 = new ToolTipController();
        //private void chartControl1_MouseClick(object sender, MouseEventArgs e)
        //{
        //    // Obtain hit information under the test point.
        //    ChartHitInfo hi = chartControl1.CalcHitInfo(e.X, e.Y);

        //    // Obtain the series point under the test point.
        //    SeriesPoint point = hi.SeriesPoint;

        //    // Check whether the series point was clicked or not.
        //    if (point != null)
        //    {
        //        // Obtain the series point argument.
        //        string argument = "Argument: " + (DateTime.Parse(point.Argument)).ToShortDateString();

        //        // Obtain series point values.
        //        string values = "Value(s): " + point.Values[0].ToString();
        //        if (point.Values.Length > 1)
        //        {
        //            for (int i = 1; i < point.Values.Length; i++)
        //            {
        //                values = values + ", " + point.Values[i].ToString();
        //            }
        //        }

        //        // Show the tooltip.
        //        toolTipController1.ShowHint(argument + "\n" + values, "SeriesPoint Data");
        //    }
        //    else
        //    {
        //        // Hide the tooltip.
        //        toolTipController1.HideHint();
        //    }
        //}


        bool LineMarker = false;
        void comboPeriod_EditValueChanged(object sender, EventArgs e)
        {
            RefreshCurr2(0);
            chkLineMarker.Tag = (comboPeriod.EditValue.ToString() == "Month");
            ChkMarkerChanged();
        }

        void comboChartType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < chartControl1.Series.Count; i++)
                    chartControl1.Series[i].ChangeView((ViewType)comboChartType.SelectedItem);

                //chartControl1.SeriesTemplate.ChangeView((ViewType)comboChartType.SelectedItem);
                //chartControl1.SeriesTemplate.ArgumentScaleType = DevExpress.XtraCharts.ScaleType.DateTime;
                //(chartControl1.Diagram as XYDiagram).AxisX.DateTimeMeasureUnit = DateTimeMeasurementUnit.Day;

                if (chartControl1.Diagram is Diagram3D)
                {
                    Diagram3D diagram = (Diagram3D)chartControl1.Diagram;
                    diagram.RuntimeRotation = true;
                    diagram.RuntimeZooming = true;
                    diagram.RuntimeScrolling = true;
                }
                else if (chartControl1.Diagram is XYDiagram2D)
                {
                    XYDiagram2D diagram = (XYDiagram2D)chartControl1.Diagram;
                    diagram.EnableAxisXScrolling = true;
                    diagram.EnableAxisXZooming = true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        void chartControl1_MouseWheel(object sender, MouseEventArgs e)
        {
            //RefreshCurr2(Math.Sign(e.Delta));
        }

        void gridControl1_MouseWheel(object sender, MouseEventArgs e)
        {
            RefreshCurr(Math.Sign(e.Delta));
        }

        private DataTable CreateChartData(int rowCount)
        {
            // Create an empty table.
            DataTable table = new DataTable("Table1");

            // Add two columns to the table.
            table.Columns.Add("Argument", typeof(Int32));
            table.Columns.Add("Value", typeof(Int32));

            // Add data rows to the table.
            Random rnd = new Random();
            DataRow row = null;
            for (int i = 0; i < rowCount; i++)
            {
                row = table.NewRow();
                row["Argument"] = i;
                row["Value"] = rnd.Next(100);
                table.Rows.Add(row);
            }

            return table;
        }

        private void OA(object sender, EventArgs e)
        {
            // Create a chart.
            ChartControl chart = new ChartControl();

            // Create an empty Bar series and add it to the chart.
            Series series = new Series("Series1", ViewType.Bar);
            chart.Series.Add(series);

            // Generate a data table and bind the series to it.
            series.DataSource = CreateChartData(50);

            // Specify data members to bind the series.
            series.ArgumentScaleType = ScaleType.Numerical;
            series.ArgumentDataMember = "Argument";
            series.ValueScaleType = ScaleType.Numerical;
            series.ValueDataMembers.AddRange(new string[] { "Value" });

            // Set some properties to get a nice-looking chart.
            ((SideBySideBarSeriesView)series.View).ColorEach = true;
            ((XYDiagram)chart.Diagram).AxisY.Visibility = DefaultBoolean.False;
            chart.Legend.Visibility = DefaultBoolean.False;

            // Dock the chart into its parent and add it to the current form.
            chart.Dock = DockStyle.Fill;
            this.Controls.Add(chart);
        }


        void DrawChart()
        {
            try
            {
                chartControl1.RefreshDataOnRepaint = false;
                chartControl1.CacheToMemory = true;
                chartControl1.RuntimeHitTesting = false;
                //((XYDiagram)chartControl1.Diagram).AxisX.DateTimeMeasureUnit = CalculateDateTimeMeasureUnit(chartControl1.Series[0].Points, chartControl1.Width, 100);

                chartControl1.DataSource = bsChart;
                Series series;
                foreach (string sec in "EUR;GBP;USD;EUR/USD".Split(';'))    //;EUR/USD
                {
                    if (sec.Contains("/"))
                        series = new Series(sec, ViewType.Point);
                    else
                        series = new Series(sec, ViewType.Line);

                    // Cpecify ScaleTypes
                    series.ArgumentScaleType = ScaleType.DateTime;
                    series.ValueScaleType = ScaleType.Numerical;

                    // Bound series to data
                    series.ArgumentDataMember = "Tarih";
                    series.ValueDataMembers.AddRange(new string[] { sec }); //"Selling"
                    //series.SummaryFunction = "AVERAGE(" + sec + ")";
                    //series.DataFilters.Add(new DataFilter("id", typeof(string).FullName, DataFilterCondition.Equal, series.Name));

                    series.LabelsVisibility = DefaultBoolean.True;
                    chartControl1.Series.Add(series);
                }

                XYDiagram diagram = (XYDiagram)chartControl1.Diagram;
                DevExpress.XtraCharts.Axis xAxis = diagram.AxisX;
                xAxis.Label.Angle = 270;
                xAxis.Label.EnableAntialiasing = DefaultBoolean.False;
                diagram.AxisX.Interlaced = true;
                diagram.EnableAxisXScrolling = true;
                diagram.EnableAxisXZooming = true;
                //diagram.AxisY.VisualRange.Auto = true;
                diagram.AxisY.VisualRange.MinValue = 1.2;

            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            //comboChartType.SelectedItem = ViewType.Line;
        }

        void deGun_EditValueChanged(object sender, EventArgs e)
        {
            end = deGun.DateTime;
        }

        private void RefreshCurr(int op)
        {
            ds.xTCMB1.Clear();
            GetDetails("xTCMB1", "GetCurrency2", (DateTime)deGun.EditValue, op, 0);

            gvDaily.Focus();
            deGun.EditValue = (DateTime)((DataRowView)bsDaily.Current).Row["Tarih"];
            //txtInfo.Caption = "- TCMB Döviz Kurları; " + deGun.Text;

            //((DevExpress.XtraCharts.XYDiagram)chartControl1.Diagram).AxisX.Strips.Clear();
            //((DevExpress.XtraCharts.XYDiagram)chartControl1.Diagram).AxisX.Strips.Add(new Strip("SelectedDate", (DateTime)((DataRowView)bsDaily.Current).Row["Tarih"], (DateTime)((DataRowView)bsDaily.Current).Row["Tarih"]));

            double USD = double.Parse(ds.xTCMB1.Select("Currency ='USD'", "")[0]["Buying"].ToString());
            double EUR = double.Parse(ds.xTCMB1.Select("Currency ='EUR'", "")[0]["Buying"].ToString());
            double GBP = double.Parse(ds.xTCMB1.Select("Currency ='GBP'", "")[0]["Buying"].ToString());
            lblCapraz.Text = "EUR/USD: " + String.Format("{0:#.####}", EUR / USD) + "  GBP/USD: " + String.Format("{0:#.####}", GBP / USD);

            ShiftRange(-1);
        }

        private void ShiftRange(int op)
        {
            try
            {                
                switch (comboPeriod.EditValue.ToString())
                {
                    //case "Week": start = end.AddDays(7*op); break; //Days(-deGun.DateTime.Day + 1);
                    case "Month": start = end.AddMonths(op); break;
                    case "Year": start = end.AddYears(op); break;
                    case "5Years": start = end.AddYears(5*op); break;
                }
                bsChart.Filter = "Tarih >= '" + start.ToShortDateString() + "' and Tarih <= '" + end.ToShortDateString() + "'";
                //chartControl1.RefreshData();
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }

        private void RefreshCurr2(int op)
        {
            switch (comboPeriod.EditValue.ToString())
            {
                //case "Week": end = end.AddDays(7*op); break;
                case "Month": end = end.AddMonths(op); break;
                case "Year": end = end.AddYears(op); break;
                case "5Years": end = end.AddYears(5*op); break;
            }
            ShiftRange(-1);
        }

        private void deGun_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13/*Keys.Enter*/)
            {
                gvDaily.Focus();
                RefreshCurr(0);
            }
        }
    }
}